<template>
  <div class="volunteer-apply-page">
    <el-card class="apply-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><UserFilled /></el-icon>
          <span>志愿者申请</span>
        </div>
      </template>

      <div class="apply-content">
        <!-- 提示信息 -->
        <el-alert
          title="欢迎申请成为志愿者"
          type="info"
          :closable="false"
          show-icon
          class="info-alert"
        >
          <template #default>
            <p>感谢您对流浪动物救助事业的关注和支持！请认真填写以下信息，我们将尽快审核您的申请。</p>
          </template>
        </el-alert>

        <!-- 申请表单 -->
        <el-form
          ref="formRef"
          :model="application"
          :rules="rules"
          label-width="120px"
          label-position="left"
          class="apply-form"
        >
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="application.name"
              placeholder="请输入您的真实姓名"
              clearable
              :prefix-icon="User"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="application.phone"
              placeholder="请输入您的联系电话"
              clearable
              :prefix-icon="Phone"
              maxlength="11"
            />
          </el-form-item>

          <el-form-item label="联系地址" prop="address">
            <el-input
              v-model="application.address"
              placeholder="请输入您的详细地址"
              clearable
              :prefix-icon="Location"
            />
          </el-form-item>

          <el-form-item label="志愿者经验" prop="experience">
            <el-input
              v-model="application.experience"
              type="textarea"
              :rows="4"
              placeholder="请描述您之前的志愿者经验，如无经验可填写无"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="技能特长" prop="skills">
            <el-input
              v-model="application.skills"
              placeholder="例如：医疗护理、摄影、文案编辑、活动组织等"
              clearable
              :prefix-icon="Star"
            />
          </el-form-item>

          <el-form-item label="可用时间" prop="availability">
            <el-input
              v-model="application.availability"
              placeholder="例如：周末、工作日晚上、节假日等"
              clearable
              :prefix-icon="Clock"
            />
          </el-form-item>

          <el-form-item label="申请原因" prop="whyVolunteer">
            <el-input
              v-model="application.whyVolunteer"
              type="textarea"
              :rows="5"
              placeholder="请详细说明您为什么想成为志愿者，以及您对流浪动物救助的看法"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="倾向任务" prop="preferredTasks">
            <el-checkbox-group v-model="application.preferredTasks">
              <el-checkbox label="救助信息审核">救助信息审核</el-checkbox>
              <el-checkbox label="救助记录管理">救助记录管理</el-checkbox>
              <el-checkbox label="领养审核">领养审核</el-checkbox>
              <el-checkbox label="动物档案管理">动物档案管理</el-checkbox>
              <el-checkbox label="健康档案管理">健康档案管理</el-checkbox>
              <el-checkbox label="故事档案管理">故事档案管理</el-checkbox>
              <el-checkbox label="其他">其他</el-checkbox>
            </el-checkbox-group>
            <div class="form-tip">可选择多个任务类型</div>
          </el-form-item>

          <el-form-item>
            <div class="form-actions">
              <el-button @click="resetForm" :icon="Refresh">重置</el-button>
              <el-button
                type="primary"
                @click="submitApplication"
                :loading="submitting"
                :icon="Check"
              >
                提交申请
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  UserFilled,
  User,
  Phone,
  Location,
  Star,
  Clock,
  Refresh,
  Check
} from '@element-plus/icons-vue';

export default {
  name: 'VolunteerApply',
  components: {
    UserFilled,
    User,
    Phone,
    Location,
    Star,
    Clock,
    Refresh,
    Check
  },
  data() {
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      submitting: false,
      application: {
        name: '',
        phone: '',
        address: '',
        experience: '',
        skills: '',
        availability: '',
        whyVolunteer: '',
        preferredTasks: []
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入联系地址', trigger: 'blur' },
          { min: 5, max: 100, message: '地址长度在 5 到 100 个字符', trigger: 'blur' }
        ],
        experience: [
          { required: true, message: '请填写志愿者经验', trigger: 'blur' },
          { min: 2, max: 500, message: '经验描述长度在 2 到 500 个字符', trigger: 'blur' }
        ],
        whyVolunteer: [
          { required: true, message: '请填写申请原因', trigger: 'blur' },
          { min: 10, max: 1000, message: '申请原因长度在 10 到 1000 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    async submitApplication() {
      // 表单验证
      try {
        await this.$refs.formRef.validate();
      } catch (error) {
        ElMessage.warning('请完善表单信息');
        return;
      }

      // 确认提交
      ElMessageBox.confirm('确认提交志愿者申请吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确认提交',
        cancelButtonText: '取消'
      })
        .then(async () => {
          this.submitting = true;

          try {
            const userId = localStorage.getItem('userId');
            if (!userId) {
              ElMessage.error('请先登录');
              this.$router.push('/login');
              return;
            }

            // 处理倾向任务（数组转字符串）
            const formData = {
              ...this.application,
              userId: userId,
              preferredTasks: Array.isArray(this.application.preferredTasks)
                ? this.application.preferredTasks.join(',')
                : this.application.preferredTasks || ''
            };

            const res = await axios.post(
              'http://localhost:8080/api/user/volunteer/apply',
              formData
            );

            if (res.data.code === 200) {
              ElMessage.success(res.data.msg || '申请提交成功！我们会尽快审核您的申请');
              // 重置表单
              this.resetForm();
            } else {
              ElMessage.error(res.data.msg || '申请提交失败，请重试');
            }
          } catch (error) {
            console.error('提交申请失败:', error);
            if (error.response && error.response.data && error.response.data.msg) {
              ElMessage.error(error.response.data.msg);
            } else {
              ElMessage.error('申请提交失败，请检查网络连接后重试');
            }
          } finally {
            this.submitting = false;
          }
        })
        .catch(() => {
          // 用户取消
        });
    },

    resetForm() {
      this.$refs.formRef.resetFields();
      this.application = {
        name: '',
        phone: '',
        address: '',
        experience: '',
        skills: '',
        availability: '',
        whyVolunteer: '',
        preferredTasks: []
      };
    }
  }
};
</script>

<style scoped>
.volunteer-apply-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 88px);
}

.apply-card {
  max-width: 900px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.apply-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  border-radius: 12px 12px 0 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 20px;
  font-weight: 600;
}

.header-icon {
  font-size: 24px;
}

.apply-content {
  padding: 30px;
}

.info-alert {
  margin-bottom: 30px;
  border-radius: 8px;
}

.info-alert :deep(.el-alert__content) {
  line-height: 1.8;
}

.info-alert p {
  margin: 0;
  color: #606266;
}

.apply-form {
  margin-top: 20px;
}

.apply-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

.apply-form :deep(.el-input__wrapper) {
  border-radius: 6px;
}

.apply-form :deep(.el-textarea__inner) {
  border-radius: 6px;
  resize: vertical;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.5;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  min-width: 120px;
  height: 40px;
  font-size: 15px;
}

/* 复选框组样式优化 */
:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-checkbox:hover) {
  border-color: #409eff;
  background: #f0f9ff;
}

:deep(.el-checkbox.is-checked) {
  border-color: #409eff;
  background: #ecf5ff;
}

:deep(.el-checkbox__label) {
  padding-left: 8px;
  font-size: 14px;
  color: #606266;
}

:deep(.el-checkbox.is-checked .el-checkbox__label) {
  color: #409eff;
  font-weight: 500;
}

/* 响应式 */
@media (max-width: 768px) {
  .volunteer-apply-page {
    padding: 15px;
  }

  .apply-content {
    padding: 20px;
  }

  .apply-form {
    margin-top: 15px;
  }

  .apply-form :deep(.el-form-item__label) {
    width: 100% !important;
    text-align: left;
    margin-bottom: 8px;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .form-actions .el-button {
    width: 100%;
  }

  :deep(.el-checkbox-group) {
    flex-direction: column;
    gap: 12px;
  }

  :deep(.el-checkbox) {
    width: 100%;
  }
}
</style>

